#!/usr/bin/env python
# -*- coding:utf-8 -*-

'''
PACKET SPECIFICATION:
    packet ::= route_slice separator data_slice
    separator ::= '\t'

    route_slice   ::= action_field service_field
    action_field  ::= 'action:' action_name
    action_name   ::= 'REQUEST' | 'RESPONSE' | 'FORWARD'
    service_field ::= 'service:' service_name
    service_name  ::= letter (letter | digit)*

    data_slice ::= 'body:' data
    data       ::= base64_encode_string

    identifier ::=  (letter|"_") (letter | digit | "_")*
    letter     ::=  lowercase | uppercase
    lowercase  ::=  "a"..."z"
    uppercase  ::=  "A"..."Z"
    digit      ::=  "0"..."9"

'''

import asyncore, asynchat, socket, threading, time

HOST = "127.0.0.1"
PORT = 54344

def DEBUG(format, *args) : print format % args

class echo_client(asynchat.async_chat):

    def __init__(self):
        asynchat.async_chat.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((HOST, PORT))
        self.set_terminator('\n')
        self.buffer = ""

    def handle_connect(self):
        print "CLIENT Connecting ..."

    def collect_incoming_data(self, data):
        DEBUG('CLIENT collect: >>>%s<<<', data)
        self.buffer = self.buffer + data

    def found_terminator(self):
        print "CLIENT Received:", self.buffer
        self.buffer = ""
        self.close()    # ??? while close socket here ???

def main():
    from base64 import b64encode
    c = echo_client()
    for i in range(10) :
        msg = "action:REQUEST\tservice:ECHO\tbody:" + b64encode('#' + str(i) + ' hello, world.')
        c.push(msg + "\n")
    asyncore.loop()

if __name__ == '__main__' :
    main()
    import sys
    sys.exit(0)
